﻿using IdentityService.Domain.Aggregates.RoleAggregate;
using IdentityService.Domain.Repositories;
using Microsoft.EntityFrameworkCore;

namespace IdentityService.Infrastructure.EFRepositories
{
    public class EFRoleRepository : IRoleRepository
    {
        private readonly AppIdentityDbContext _context;
        public EFRoleRepository(AppIdentityDbContext context) => _context = context;

        public async Task AddAsync(Role role)
        {
            await _context.Role.AddAsync(role);
        }

        public void Delete(Role role)
        {
            _context.Role.Remove(role);
        }

        public async Task<Role?> FindByIdAsync(long id)
        {
            return await _context.Role.FirstOrDefaultAsync(it => it.Id == id);
        }

        public async Task<Role?> FindByIdIncludeAllAsync(long id)
        {
            return await _context.Role.Include(it => it.Permits).Include(it => it.UserAccounts)
                .FirstOrDefaultAsync(it => it.Id == id);
        }

        public async Task<Role?> FindByIdIncludeUserAccountsAsync(long id)
        {
            return await _context.Role.Include(it => it.UserAccounts).FirstOrDefaultAsync(it => it.Id == id);
        }

        public async Task<Role?> FindByIdIncludePermitsAsync(long id)
        {
            return await _context.Role.Include(it => it.Permits).FirstOrDefaultAsync(it => it.Id == id);
        }

        public async Task<bool> CheckExistByNameAsync(string name)
        {
            return await _context.Role.AnyAsync(it => it.Name == name);
        }
    }
}
